package com.urlshortener

import grails.converters.JSON;

class ShortenURLService {

	public static final int TINY_URL=1;
	public static final int IS_GD=2;
	public static final int BT_LY=4;
	public static final int GO_GL=5;
	
	
	String btlyLogin
	String btlyApiKey
	String format
	String googlApiKey
	
	def setupBtly(String login,String apikey,String format)
{
	btlyLogin=login
	btlyApiKey=apikey
	this.format=format
}

def setupGogl(String apikey)
{
	googlApiKey=apikey
}

    static transactional = false

    def shorten(String url,int serviceType) {
		 switch(serviceType)
		 {
			 case (TINY_URL):
			 TinyUrl( url)
			 case (IS_GD):
		GdURL.shorten url
			 case (BT_LY):
			 BtlyUrl( url)
			 case (GO_GL):
			 GoglURL(url)
			 default:
			 TinyUrl( url)
			 
		 }
    }
	
	def TinyUrl(String url)
	{
		TinyURL.shorten(url)
	}
	
	def GdURL(String url)
	{
		GdURL.shorten url
	}
	
	def GoglURL(String url)
	{
		
		
		if(null==googlApiKey)
		{
			return "Authentication not setup. Call setupGogl first "
		}
		
		GoGlURL.shorten apikey, url
	}
	
	def BtlyUrl(String url)
	{
		if(null==btlyLogin || null==btlyApiKey)
		{
			return "Authentication not setup. Call setupBtly first "
		}
		if(null==format)
		{
			format="json"
		}
		 BtlyURL.shorten( btlyLogin, btlyApiKey, format, url) 
	}
}
